package com.yueke.gemini.ssp.manager.interceptor;

import com.yueke.gemini.ssp.manager.common.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

/**
 * Created by admin on 2019/3/5.
 */
@Component
public class ApiInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 获取请求参数
         */
        ServletInputStream stream = request.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ( (len = stream.read(buffer)) != -1){
            outputStream.write(buffer,0,len);
        }
        outputStream.close();
        stream.close();
        String queryString = outputStream.toString();
        System.out.println(queryString);

        if (StringUtils.isEmpty(queryString)){
            ApiResult<String> apiResult = new ApiResult<>();
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(apiResult.toString());
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("[[[[[[[[[[[[[[[[[[[[[");
    }
}
